package com.bdqn.controller;

import com.bdqn.component.BlogConstants;
import com.bdqn.dao.ArticleMapper;
import com.bdqn.dao.ArticleTypeMapper;
import com.bdqn.entity.ArticleType;
import com.bdqn.entity.ArticleWithBLOBs;
import com.bdqn.entity.User;
import com.bdqn.entity.UserWithBLOBs;
import com.bdqn.service.ArticleService;
import com.bdqn.service.ArticleTypeService;
import com.bdqn.service.UserService;
import com.bdqn.util.Result;
import com.bdqn.util.TokenUtil;
import com.google.code.kaptcha.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private ArticleService articleService;


    String vpath = "client/";

    /**
     * @param user
     * @param repassword
     * @param captcha
     * @param session
     * @param model
     * @return
     */
    @PostMapping("/register")
    public String register(UserWithBLOBs user, String repassword, String captcha,
                           HttpSession session, Model model) {
        String sysCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Result rs = userService.register(user, repassword, captcha, sysCaptcha);
        if (rs.isSuccess()) {
            //重定向登录：
            return "redirect:/client/regSuccess.html";
        }
        //转发到注册页
        model.addAttribute("msg", rs.getContent());
        return vpath + "register";
    }

    @PostMapping("/registerJson")
    @ResponseBody
    public Result registerJson(UserWithBLOBs user, String repassword, HttpSession session, String captcha) {

        String sysCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        return userService.register(user, repassword, captcha, sysCaptcha);
    }

    /**
     * 异步
     *
     * @param user
     * @param session
     * @param captcha
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result<UserWithBLOBs> loginJson(UserWithBLOBs user, HttpSession session, String captcha) {

        String sysCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Result<UserWithBLOBs> rs = userService.checkLogin(user, captcha, sysCaptcha);
        if (rs.isSuccess()) {
            session.setAttribute(BlogConstants.LOGIN_SESSION_KEY, rs.getData());
        }
        return rs;
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(BlogConstants.LOGIN_SESSION_KEY);
        return "redirect:/";
    }

    /**
     * 修改个人信息
     *
     * @param user
     * @param hobbys
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/updateUserInfo")
    @ResponseBody
    public Result updateUserInfo(UserWithBLOBs user, String[] hobbys,
                                 @RequestParam(name = "file", required = false) CommonsMultipartFile file,
                                 @RequestParam(name = "bannerFile", required = false) CommonsMultipartFile bannerFile
        , HttpServletRequest request) {

           return userService.updateUserInfo(request, user, hobbys, file,bannerFile);
    }

    /**
     * 更换头像
     */
    @RequestMapping("/changePhoto")
    @ResponseBody
    public Result changePhoto(@RequestParam(name = "file", required = true) CommonsMultipartFile file, HttpServletRequest request) {

        return userService.updateUserPhoto(request, file);
    }

    /**
     * 更换密码
     *
     * @param originPass
     * @param pass
     * @param repass
     * @param request
     * @return
     */
    @RequestMapping("/rescrPass")
    @ResponseBody
    public Result rescrPass(String originPass, String pass, String repass
        , HttpServletRequest request) {
        return userService.updatePass(originPass, pass, repass, request);
    }

    /**
     * 个人博客页面
     *
     * @param centerpath
     * @param pageName
     * @param model
     * @return
     */
    @GetMapping("/{pageName}/{centerpath}")
    public String userCenter(@PathVariable("centerpath") String centerpath,
                             @PathVariable("pageName") String pageName,
                             @RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
                             @RequestParam(name = "articeTid", defaultValue = "1") Integer articeTid, Model model,
                             HttpSession session) {
        String token = (String) session.getAttribute("token");
        if (StringUtils.isBlank(token)){
            session.setAttribute("token",TokenUtil.getToken(session));
        }
        Result rs = userService.userCenter(centerpath, pageName, pageIndex, articeTid, session);
        if (rs.isSuccess()) {
            if ("index".equals(pageName)) {
                model.addAttribute("articeTypes", articleTypeService.getAllArticleType());
                model.addAttribute("articeTid", articeTid);
            }
            model.addAttribute(pageName.equals("about")?"blogUser":"page", rs.getData());
            model.addAttribute("pageName", pageName);
            return "client/" + pageName;
        }
        return "client/404";
    }

    /**
     * 查看文章
     * @param centerpath
     * @param pageName
     * @param articleUuid
     * @param model
     * @return
     */
    @GetMapping("/{pageName}/{centerpath}/{articleUuid}")
    public String reader(@PathVariable("centerpath") String centerpath,
                         @PathVariable("pageName") String pageName,
                         @PathVariable("articleUuid") String articleUuid,Model model,HttpSession session){

        ArticleWithBLOBs article = articleService.getArticleByld(articleUuid);
        articleService.updatePlusReader(article.getUuid());
        session.setAttribute(BlogConstants.USER_SESSION_KEY,userService.getUserByCenterPath(centerpath));
        model.addAttribute("article",article);
        session.setAttribute("token", TokenUtil.getToken(session));
        return "client/details" ;
    }

}
